package com.hefan.api.aop.appTask;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Repository;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hefan.activity.bean.AppTaskInfo;
import com.hefan.activity.bean.AppTaskRelation;
import com.hefan.activity.bean.AppTaskVo;
import com.hefan.api.service.activity.AppTaskLocalService;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;

/**
 * 首次进入直播间任务  type =8
 * @ClassName:  FirstJoinRoomAop   
 * @Description:TODO(这里用一句话描述这个类的作用)   
 * @author: LiTeng  
 * @date:   2016年11月16日 下午5:40:04   
 *
 */
@Aspect
@Repository
public class FirstJoinRoomAop {

	@Resource
	AppTaskLocalService appTaskLocalService;
	
	private Logger logger = LoggerFactory.getLogger(FirstJoinRoomAop.class);
	
	@AfterReturning(value="execution(* com.hefan.api.controller.live.LiveController.joinLiveRoom(..))",returning="rtv")
    public void afterInsertMethod(JoinPoint jp, Object rtv) throws Throwable {  
		//返回成功才处理
		try {
			if(JSON.parseObject(rtv.toString()).getString("code").equals("1000")){
				HttpServletRequest request = (HttpServletRequest) jp.getArgs()[0];
			    Map paramMap = HttpUtils.initParam(request, Map.class);
				String userId = MapUtils.getStrValue(paramMap, "userId", "");
				System.out.println("userId:"+userId);
				if(StringUtils.isNotBlank(userId)){
					this.firstJoinDeal(userId);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("首次进入直播间任务处理失败:"+e.getMessage());
		}
        
    }
	
	private boolean firstJoinDeal(String userId){
		AppTaskInfo apt = appTaskLocalService.getAppTaskInfoListByType(8);
		if(new Date().before(apt.getBeginTime()) || new Date().after(apt.getEndTime()) || apt.getDeleteFlag() !=0){
			return false;
		}
		AppTaskRelation taskRe = appTaskLocalService.getAppTaskRelationByUserId(userId);
		List<AppTaskVo> voList = new ArrayList<AppTaskVo>();
		if(taskRe == null){
			//新增
			AppTaskVo vo = new AppTaskVo();
			vo.setTaskType(apt.getTaskType());
			vo.setTaskName(apt.getTaskName());
			//任务说明
			vo.setTaskExplain(apt.getTaskExplain());
			//任务图标
			vo.setTaskIcon(apt.getTaskIcon());
			//完成能获得的经验
			vo.setExpValue(apt.getExpValue());
			//完成能获得的饭票
			vo.setTicketValue(apt.getTicketValue());
			//状态  1-未领取  2-未完成  4-已领取
			vo.setTaskStatus(1);
			//进度
			vo.setSetbacks(apt.getScaleValue());
			//总刻度 （任务完成需要的数量）
			vo.setScaleValue(apt.getScaleValue());
			voList.add(vo);
			String tasksJson = JSONObject.toJSONString(voList);
			AppTaskRelation atr =  new AppTaskRelation();
			atr.setUserId(userId);
			atr.setTasksJson(tasksJson);
			atr.setDeleteFlag(0);
			atr.setCreateTime(new Date());
			atr.setUpdateTime(new Date());
			appTaskLocalService.saveOrUpAppTaskRelation(atr);
		}else{
			//修改
			if(taskRe !=null && StringUtils.isNotBlank(taskRe.getTasksJson())){
	    		voList = JSON.parseArray(taskRe.getTasksJson(), AppTaskVo.class);
	    	}
			int f=0;
			for(int i=0;i<voList.size();i++){
				AppTaskVo vo = voList.get(i);
				if(vo.getTaskType()==8){
					f=1;
				}
			}
			if(f==0){
				AppTaskVo vo = new AppTaskVo();
				vo.setTaskType(apt.getTaskType());
				vo.setTaskName(apt.getTaskName());
				//任务说明
				vo.setTaskExplain(apt.getTaskExplain());
				//任务图标
				vo.setTaskIcon(apt.getTaskIcon());
				//完成能获得的经验
				vo.setExpValue(apt.getExpValue());
				//完成能获得的饭票
				vo.setTicketValue(apt.getTicketValue());
				//状态  1-未领取  2-未完成  4-已领取
				vo.setTaskStatus(1);
				//进度
				vo.setSetbacks(apt.getScaleValue());
				//总刻度 （任务完成需要的数量）
				vo.setScaleValue(apt.getScaleValue());
				voList.add(vo);
				String tasksJson = JSONObject.toJSONString(voList);
				taskRe.setTasksJson(tasksJson);
				appTaskLocalService.saveOrUpAppTaskRelation(taskRe);
			}
		}
		return true;
	}
}
